﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

/// <summary>
/// Summary description for MyEncryption1
/// </summary>
public class MyEncryption1
{
	public MyEncryption1()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    public static string Encrypt(string toEncrypt, string key, bool useHashing)
    {
        if (toEncrypt == "")
        {
            return "";
        }

        byte[] keyArray;
        var toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        var tdes = new TripleDESCryptoServiceProvider
        {
            Key = keyArray,
            Mode = CipherMode.ECB,
            Padding = PaddingMode.PKCS7
        };

        var cTransform = tdes.CreateEncryptor();
        var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        /////////
        string tinh_temp_encrypt = Convert.ToBase64String(resultArray, 0, resultArray.Length);
        /////////
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    public static string Decrypt(string toDecrypt, string key, bool useHashing)
    {
        if (toDecrypt == "")
        {
            return "";
        }

        byte[] keyArray;
        var toEncryptArray = Convert.FromBase64String(toDecrypt);

        if (useHashing)
        {
            var hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        var tdes = new TripleDESCryptoServiceProvider
        {
            Key = keyArray,
            Mode = CipherMode.ECB,
            Padding = PaddingMode.PKCS7
        };

        var cTransform = tdes.CreateDecryptor();
        byte[] resultArray;
        try
        {
            resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        }
        catch
        {
            throw new ArgumentException("File Data is bad.");
        }
        //////////////
        string tinh_temp_decrypt = UTF8Encoding.UTF8.GetString(resultArray);
        //////////////
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
}